<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="tableForm" :inline="true" :model="listQuery">
        <el-row>
          <el-col :span="4">
            <el-form-item label="商品名称" prop="product_title">
              <el-input
                v-model="listQuery.product_title"
                @keyup.enter.native="handleFilter"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="商品ID" prop="product_id">
              <el-input
                v-model="listQuery.product_id"
                @keyup.enter.native="handleFilter"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="订单号" prop="order_id">
              <el-input
                v-model="listQuery.order_id"
                @keyup.enter.native="handleFilter"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="推广用户" prop="r_user">
              <el-input
                v-model="listQuery.r_user"
                @keyup.enter.native="handleFilter"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="付款时间" prop="pay_at">
              <el-date-picker
                v-model="listQuery.pay_at"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="7">
            <el-form-item label="收货时间" prop="end_time">
              <el-date-picker
                v-model="listQuery.end_time"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="结算时间" prop="settlement_time">
              <el-date-picker
                v-model="listQuery.settlement_time"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="识别码" prop="rid">
              <el-input
                v-model="listQuery.rid"
                @keyup.enter.native="handleFilter"
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="rid" prop="order_rid">
              <el-input
                v-model="listQuery.order_rid"
                @keyup.enter.native="handleFilter"
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="补贴状态" prop="is_subsidy">
              <el-select v-model="listQuery.is_subsidy" placeholder="请选择">
                <el-option label="享受" :value="1" />
                <el-option label="不享受" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-button @click="resetForm('tableForm')">重置</el-button>
            <el-button
              v-waves
              type="primary"
              icon="el-icon-search"
              @click="handleFilter"
            >
              {{ $t("table.search") }}
            </el-button>
            <el-button
              type="success"
              icon="el-icon-download"
              :loading="isDowning"
              @click="handleDown"
              >导出订单</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-tabs v-model="listQuery.type" type="card" @tab-click="getList">
      <el-tab-pane label="全部" name="99" />
      <el-tab-pane label="已付款" name="1" />
      <el-tab-pane label="已收货" name="2" />
      <el-tab-pane label="已结算" name="3" />
      <el-tab-pane label="已失效" name="4" />
    </el-tabs>
    <div class="totalBox">
      <div>累计付款金额：{{ totalNum.total_pay_amount }}</div>
      <div>累计收货金额：{{ totalNum.total_receipt_amount }}</div>
      <div>累计结算金额：{{ totalNum.total_settlement_amount }}</div>
      <div>累计补贴金额：{{ totalNum.total_subsidy_amount }}</div>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column
        label="商品信息"
        prop="nickname"
        align="center"
        width="300"
      >
        <template slot-scope="{ row }">
          <div class="goodsInfo">
            <el-avatar
              :src="row.product_picture"
              :size="50"
              fit="contain"
              shape="square"
            />
            <div class="textBox">
              <el-tooltip
                effect="dark"
                placement="top"
                :content="row.product_title"
              >
                <div class="content">商品标题：{{ row.product_title }}</div>
              </el-tooltip>
              <el-tooltip effect="dark" placement="top" :content="row.order_id">
                <div class="content">订单号：{{ row.order_id }}</div>
              </el-tooltip>
              <div class="content">付款时间：{{ row.pay_at }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="rid" prop="order_rid" align="center">
        <template slot-scope="{ row }">
          {{ row.order_rid || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="推广用户" prop="nickname" align="center">
        <template slot-scope="{ row }">
          {{ row.user.nickname }}
        </template>
      </el-table-column>
      <el-table-column label="付款金额" prop="order_amount" align="center" />
      <el-table-column label="补贴金额" prop="products" align="center">
        <template slot-scope="{ row }">
          {{ row.products.subsidy_amount }}
        </template>
      </el-table-column>
      <el-table-column label="订单状态" prop="status" align="center">
        <template slot-scope="{ row }">
          {{ row.status | statusFilter }}
        </template>
      </el-table-column>
      <el-table-column
        label="收货时间"
        prop="end_time"
        align="center"
        width="170"
      >
        <template slot-scope="{ row }">
          <span>{{ row.end_time || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结算状态" prop="is_settlement" align="center">
        <template slot-scope="{ row }">
          {{ row.is_settlement | settlementFilter }}
        </template>
      </el-table-column>
      <el-table-column
        label="结算时间"
        prop="settlement_time"
        align="center"
        width="170"
      >
        <template slot-scope="{ row }">
          <span>{{ row.settlement_time || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.actions')"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            补贴分佣明细
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :visible.sync="dialogPvVisible" title="分佣明细">
      <el-table
        :data="pvData"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="headimgurl" label="会员昵称" width="300">
          <template slot-scope="{ row }">
            <div class="goodsInfo">
              <el-avatar
                :src="row.user.headimgurl"
                :size="50"
                fit="contain"
                @error="errorHandler"
              >
                <img
                  src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                />
              </el-avatar>
              <div class="textBox">
                <el-tooltip
                  effect="dark"
                  placement="top"
                  :content="row.user.nickname"
                >
                  <div class="content">昵称：{{ row.user.nickname }}</div>
                </el-tooltip>
                <div class="content">ID: {{ row.user.id }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="分佣类型">
          <template slot-scope="{ row }">
            {{ row.type | typeFilter }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="分佣金额" />
        <el-table-column prop="status" label="结算状态">
          <template slot-scope="{ row }">
            {{ row.status | commissionFilter }}
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="danger" @click="handleAgain">重新分佣</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchOrderList,
  commissionDetails,
  commissionAgain,
} from "@/api/index";
import waves from "@/directive/waves"; // waves directive
import Axios from "axios";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { getToken } from "@/utils/auth";
export default {
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: "待支付",
        1: "已付款",
        2: "已失效",
        3: "已收货",
        4: "已退款",
      };
      return statusMap[status];
    },
    settlementFilter(status) {
      const statusMap = {
        1: "未结算",
        2: "已结算",
      };
      return statusMap[status];
    },
    typeFilter(status) {
      const statusMap = {
        1: "分享收益",
        2: "佣金收益",
      };
      return statusMap[status];
    },
    commissionFilter(status) {
      const statusMap = {
        1: "已结算",
        2: "未结算",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      isDowning: false,
      activeName: "first",
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 10,
        type: "99",
      },
      sortOptions: [
        { label: "ID Ascending", key: "+id" },
        { label: "ID Descending", key: "-id" },
      ],
      statusOptions: ["published", "draft", "deleted"],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        type: "",
        status: "published",
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "Edit",
        create: "Create",
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [
          { required: true, message: "type is required", trigger: "change" },
        ],
        timestamp: [
          {
            type: "date",
            required: true,
            message: "timestamp is required",
            trigger: "change",
          },
        ],
        title: [
          { required: true, message: "title is required", trigger: "blur" },
        ],
      },
      downloadLoading: false,
      totalNum: {
        total_pay_amount: 0,
        total_receipt_amount: 0,
        total_settlement_amount: 0,
        total_subsidy_amount: 0,
      },
      order_id: 0,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleAgain() {
      commissionAgain({ order_id: this.order_id }).then(() => {
        this.$message({
          type: "success",
          message: "操作成功",
        });
        this.dialogPvVisible = false;
      });
    },
    errorHandler() {
      return true;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getList() {
      const params = JSON.parse(JSON.stringify(this.listQuery));
      if (params.pay_at && params.pay_at.length) {
        params.pay_at = params.pay_at.join(",");
      } else {
        params.pay_at = "";
      }
      if (params.end_time && params.end_time.length) {
        params.end_time = params.end_time.join(",");
      } else {
        params.end_time = "";
      }
      if (params.settlement_time && params.settlement_time.length) {
        params.settlement_time = params.settlement_time.join(",");
      } else {
        params.settlement_time = "";
      }
      this.listLoading = true;
      fetchOrderList(params).then((response) => {
        this.list = response.data.list;
        this.total = response.data.total;
        Object.assign(this.totalNum, response.data);
        this.listLoading = false;
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    copyWithoutPageLimit(obj) {
      const { limit, page, ...rest } = obj;
      return Object.assign({}, rest);
    },
    handleDown() {
      this.isDowning = true;
      const data = this.copyWithoutPageLimit(this.listQuery);
      const params = JSON.parse(JSON.stringify(data));
      if (params.pay_at && params.pay_at.length) {
        params.pay_at = params.pay_at.join(",");
      } else {
        params.pay_at = "";
      }
      if (params.end_time && params.end_time.length) {
        params.end_time = params.end_time.join(",");
      } else {
        params.end_time = "";
      }
      if (params.settlement_time && params.settlement_time.length) {
        params.settlement_time = params.settlement_time.join(",");
      } else {
        params.settlement_time = "";
      }
      Axios({
        method: "post",
        url: process.env.VUE_APP_BASE_API + "/export_order",
        params: params,
        responseType: "blob",
        headers: { "access-token": getToken() },
      })
        .then((res) => {
          this.isDowning = false;
          this.$message.success("下载成功");
          const blob = new Blob([res.data]);
          const downloadElement = document.createElement("a");
          const href = window.URL.createObjectURL(blob); // 创建下载的链接
          downloadElement.href = href;
          downloadElement.download = "订单明细.xls"; // 下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); // 点击下载
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放掉blob对象
        })
        .catch((err) => {
          this.isDowning = false;
          this.$message.error(err.msg);
        });
    },
    handleUpdate(row) {
      this.order_id = row.order_id;
      commissionDetails({ order_id: row.order_id }).then((response) => {
        this.pvData = response.data;
        this.dialogPvVisible = true;
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.goodsInfo {
  display: flex;
  align-items: center;
  .textBox {
    text-align: left;
    margin-left: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .content {
      width: 200px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
.totalBox {
  font-size: 14px;
  font-weight: bold;
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}
</style>
